
const db = require('../db/index')
const bcrypt = require('bcryptjs')
const sql = 'select id , username , user_pic from user where id=?'

exports.getUserinfo = (req, res) => {
  db.query(sql, req.user.id, (err, results) => {
    if (err) return res.cc(err)
    if (results.length !== 1) return res.cc('获取用户数据失败')
    res.send({
      status: 0,
      message: '获取用户数据成功！',
      data: results[0]
    })
  })


}
exports.updateUserInfo = (req, res) => {
  const objectUpdate = {
    username: req.body.nicname,
    email: req.body.email,
    id: req.body.id
  }
  const sql = 'update user set ? where id= ?'
  db.query(sql, [objectUpdate, req.body.id], (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('更新失败！')
    res.cc('更新成功！', 0)
  })
}
exports.updatePassword = (req, res) => {
  const sql = 'select * from user where id=?'
  console.log(req.user.id);

  db.query(sql, req.user.id, (err, results) => {
    if (err) return res.cc(err)
    if (results.length !== 1) return res.cc('用户不存在')
    const compareResult = bcrypt.compareSync(req.body.oldPwd, results[0].password)
    if (!compareResult) return res.cc('旧密码错误！')

    const sqlstr = 'update user set password=? where id = ?'
    const newPwd = bcrypt.hashSync(req.body.newPwd, 10)
    db.query(sqlstr, [newPwd, req.user.id], (err, results) => {
      if (err) return res.cc(err)
      if (results.affectedRows !== 1) return res.cc('更新密码失败！')
      res.cc('更新密码成功！', 0)
    })
  })


}
exports.updateAvatar = (req, res) => {
  const sql = 'update user set user_pic =? where id = ?'
  db.query(sql, [req.body.avatar, req.user.id], (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('更新头像失败！')
    res.cc('更新头像成功！', 0)
  })
}